package websocket

import (
	"common/response"
	"errors"
	"fmt"
	websocket2 "gateway/websocket/Client"
	"github.com/gorilla/websocket"
	"github.com/rs/xid"
	"log"
	"net/http"
	"time"
)

type Params struct {
	W http.ResponseWriter
	R *http.Request
	//ResponseHeader http.Header
	DeviceId string
}

// Start http中接受token
func Start(w http.ResponseWriter, r *http.Request, DeviceId string) {
	//w.Header("/ws")

	if DeviceId == "" {
		w.WriteHeader(401)
		response.Response(w, nil, errors.New("invalid DeviceId"))
		return
	}
	Params := Params{
		W:        w,
		R:        r,
		DeviceId: DeviceId,
	}
	MessageNotify(Params)
}

// MessageNotify 建立websocket链接
func MessageNotify(params Params) {
	// TODO: 鉴权
	fmt.Println("")
	// 将http升级为websocket
	conn, err := (&websocket.Upgrader{
		// 1. 解决跨域问题
		CheckOrigin: func(r *http.Request) bool {
			return true
		},
	}).Upgrade(params.W, params.R, nil) // 升级
	if err != nil {
		response.Response(params.W, nil, err)
		return
	}

	// 创建一个实例连接
	ConnId := xid.New().String()
	client := &websocket2.Client{
		ID:            ConnId, // 连接id
		AccountId:     fmt.Sprintf("%s", params.DeviceId),
		HeartbeatTime: time.Now().Unix(),
		Socket:        conn,
	}

	// 用户注册到用户连接管理
	websocket2.RegisterChan <- client
	// 读取信息
	go func() {
		defer func() {
			if r := recover(); r != nil {
				fmt.Println("阅读")
				log.Printf("MessageNotify read panic: %+v\n", r)
			}
		}()

		client.Read()
	}()

}

// RunStart 检测链接
func RunStart() {
	//logic.SetDB(db)
	go func() {
		defer func() {
			websocket2.Start()
			websocket2.Register()
		}()
	}()
}
